/**
 * 添加或者修改页面
 */
var MainInfoInfoDlg = {
    data: {
        id: "",
        isDel: "",
        relXqId: "",
        wxXm: "",
        tswxXm: "",
        sgfa: "",
        gcys: "",
        ftl: "",
        showDay: "",
        startDate: "",
        state: "",
        createPerson: "",
        createDate: "",
        updatePerson: "",
        updateDate: ""
    }
};


layui.use(['form', 'admin', 'ax', 'laydate', 'upload', 'formSelects', 'tree', 'layer'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var tree = layui.tree;
    var layer = layui.layer;
    var upload = layui.upload;


    var houseList = '';
    var fileList = [];

    $.ajax(Feng.ctxPath + '/xqInfo/listAll', {
        async: false,
        success: function (res) {
            // console.log(res)
            $("#relXqId").empty();
            $("#relXqId").append("<option value=''>请选择小区</option>");
            for (let i = 0; i < res.length; i++) {
                $("#relXqId").append(new Option(res[i].xqName, res[i].id))
            }
            //重新渲染
            form.render("select");
        }
    })

    $("#showDay").blur(function () {
        let value = $("#showDay").val();
        value = value.replace(/[^\d]/g, '').replace(/^0{1,}/g, '');
        if (value != '')
            value = parseFloat(value).toFixed(0);
        else
            value = parseFloat(5).toFixed(0);
        $("#showDay").val(value);
    })

    $("#gcys").blur(function () {
        let value = $("#gcys").val();
        value = value.replace(/[^\d]/g, '').replace(/^0{1,}/g, '');
        if (value != '')
            value = parseFloat(value).toFixed(0);
        else
            value = parseFloat(0).toFixed(0);
        $("#gcys").val(value);
    })

    $("#ftl").blur(function () {
        let value = $("#ftl").val();
        value = value.replace(/[^\d]/g, '').replace(/^0{1,}/g, '');
        if (value > 100) {
            $("#ftl").val(0);
        } else {
            if (value != '')
                value = parseFloat(value).toFixed(0);
            else
                value = parseFloat(0).toFixed(0);
            $("#ftl").val(value);
        }
    })

    $("#relXqId").val(Feng.getUrlParam("relXqId"))
    //重新渲染
    form.render("select");


    var date = new Date();
    // console.log(date.getFullYear().toString() + "-" + (date.getMonth() + 1).toString() + "-" + date.getDay())
    //渲染时间选择框
    var laydate = layui.laydate;
    laydate.render({
        elem: '#startDate' //指定元素
        // TODO 正式上线打开
        // , min: date.getFullYear().toString() + "-" + (date.getMonth() + 1).toString() + "-" + date.getDay()
    });


    //渲染时间选择框
    var laydate = layui.laydate;
    laydate.render({
        elem: '#createDate' //指定元素
    });


    //渲染时间选择框
    var laydate = layui.laydate;
    laydate.render({
        elem: '#updateDate' //指定元素
    });

    var arr = ''
    $("#chooseUser").click(function () {
        var index = layer.open({
            title: '选择用户',
            content: Feng.ctxPath + "/mainInfo/chooseUser?relXqId=" + Feng.getUrlParam("relXqId"),
            type: 2,
            area: ['50%', '70%'],
            maxmin: true,
            // closeBtn: 0,
            success: function (layero) {
                layero.find('.layui-layer-min').remove();
                layero.find('.layui-layer-max').remove();
            },
            end: function () {
                if (sessionStorage.getItem("arr")) {
                    arr = sessionStorage.getItem("arr").split(",")
                    // console.log(arr)
                    // console.log(arr.length)
                    $("#userNumber").val(arr.length)
                    $("#ftl").val(Math.round(1 / arr.length * 10000) / 100)
                    houseList = arr
                    // console.log(houseList)
                } else {
                    $("#userNumber").val("")
                    $("#ftl").val("")
                }
            }
        })
    })

    //多图片上传
    upload.render({
        elem: '#pictureUpload',
        //改成您自己的上传接口
        url: "",
        multiple: true,
        acceptMime: 'image/*',
        auto: false,
        bindAction: '#btnSubmit',
        number: 9,
        choose: function (obj) {
            let curFiles = obj.pushFile();
            let files = curFiles; //将每次选择的文件追加到文件队列
            // 文件数量超限提醒
            if (Object.keys(curFiles).length > 9) {
                layer.msg('图片数量超过9张');
            }
            // console.log(obj)
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                if (Object.keys(curFiles).length > 9) {
                    delete files[index]
                    return;
                }
                fileList.push(result)
                // console.log(result)
                // if (index <= 9) {
                $('#preLookPicture').append('<div class="image-container layui-inline" id="container' + index + '"><div class="delete-css"><button id="upload_img_' + index + '" class="layui-btn layui-btn-danger layui-btn-xs">删除</button></div>' +
                    '<img id="showImg' + index + '" style="width: 150px; margin:10px;cursor:pointer;"src="' + result + '" alt="' + file.name + '"></div>')

                //删除某图片
                $("#upload_img_" + index).bind('click', function () {
                    // delete files[index];
                    let array = index.split("-")
                    fileList.splice(parseInt(array[1]), parseInt(array[1]))
                    $("#container" + index).remove();
                });

                //某图片放大预览
                $("#showImg" + index).bind('click', function () {
                    var width = $("#showImg" + index).width();
                    var height = $("#showImg" + index).height();
                    var scaleWH = width / height;
                    var bigH = 600;
                    var bigW = scaleWH * bigH;
                    if (bigW > 900) {
                        bigW = 900;
                        bigH = bigW / scaleWH;
                    }

                    // 放大预览图片
                    layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 1,
                        shadeClose: true,
                        area: [bigW + 'px', bigH + 'px'], //宽高
                        content: "<img width='" + bigW + "' height='" + bigH + "' src=" + result + " />"
                    });
                });
                // }else{
                //     layer.open({
                //         content: "<div style='font-size: 15px'>最多上传9张图片</div>"
                //     });
                // }

            });
        },
        before: function (obj) {
            // obj.preview(function (index, file, result) {
            //     fileList.push(result)
            // });
            // JSON.stringify(fileList)
        },
        done: function (res) {
            //上传完毕
        }
    });


    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        if (data.field.ftl != 100) {
            data.field.ftl = '0.' + data.field.ftl
        } else {
            data.field.ftl = '1'
        }
        data.field.file_length = fileList.length
        fileList = JSON.stringify(fileList)
        data.field.fileList = fileList
        var arr1 = new Array();
        $("input:checkbox[name='tswx_xm']:checked").each(function (i) {
            arr1[i] = $(this).val();
        });
        data.field.tswx_xm = arr1.join(",");//将数组合并成字符串
        for (let i = 0; i < houseList.length; i++) {
            parseInt(houseList[i])
        }
        houseList = JSON.stringify(houseList)
        data.field.houseList = houseList
        console.log(data.field)
        // return false;
        // return;
        var ajax = new $ax(Feng.ctxPath + "/mainInfo/addItem", function (data) {
            sessionStorage.removeItem("arr")
            Feng.success("添加成功！");
            window.location.href = Feng.ctxPath + '/mainInfo'
        }, function (data) {
            Feng.error("添加失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.start();

        return false;
    });

    $('#cancel').click(function () {
        sessionStorage.removeItem("arr")
        window.location.href = Feng.ctxPath + '/mainInfo'
    });

});